<?php

namespace NewMember\controller;


require_once("common/view/Page.php");
require_once("common/view/PageView.php");
require_once("login/model/LoginModel.php");
require_once("NewMember/view/RegisterMemberView.php");
require_once("NewMember/model/ValidateNewUsersCredentials.php");

// kalla på en view klass för att visa formulär.
class RegisterMemberController
{
	/**
	 * @var common\view\PageView
	 */
	private $pageView;

	/**
	 * @var NewMember\view\registerMemberView
	 */
	private $registerMemberView;

	/**
	 * @var NewMember\model\validateNewUserCredentials
	 */
	private $validateNewUserCredentials;





	public function __construct()
	{
		$this->pageView = new \common\view\PageView();
		$this->registerMemberView = new \NewMember\View\RegisterMemberView();
		$this->validateNewUserCredentials = new \NewMember\model\ValidateNewUsersCredentials();
	}



	public function GetRegisterMemberPage()
	{
		$title = "Registrera ny medlem";

		$previousUsernameValue =  $this->validateNewUserCredentials->getCreateUsernameSession();
		$errorMessage = $this->validateNewUserCredentials->getCreateErrorMessage();
		$body = $this->registerMemberView->RegisterMemberPage($errorMessage,$previousUsernameValue);	
		$page = new \common\view\Page($title, $body);

		return $this->pageView->GetXHTML10StrictPage($page);	
	}



	public function IfPostValidateRegisterInfo()
	{
		if($this->CheckIfPost()) // TODO: Kanske kolla om det är ?create också, ir nått liknande.
		{
			$username = $this->registerMemberView->getRegisterUsename();
			$password = $this->registerMemberView->getRegisterPassword();
			$password2 = $this->registerMemberView->getRegisterPassword2();

			if($this->validateNewUserCredentials->
			   ValidateAndSaveCredentials($username, $password, $password2)) 
			{
				$userCredentials = $this->validateNewUserCredentials->createUserCredentials($username, $password);

				if(!$this->validateNewUserCredentials->isUsernameTaken($userCredentials))
				{
					$this->validateNewUserCredentials->saveNewMember($userCredentials);
					header("Location: ./index.php?newMember");
				}
			}
		}
	}


	private function CheckIfPost()
	{
		if($_SERVER['REQUEST_METHOD'] == 'POST')
		{
			return true;
		}
		else
		{
			return false;
		}

	}



}